<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator" %>
<%@ taglib prefix="form" uri="http://www.springside.org.cn/tags/form" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<%--<script type="text/javascript" src="${ctx}/static/jquery/jquery-extensions/jquery.ztree.all-3.5.min.js"></script>--%>
<%--<link rel="stylesheet" type="text/css" href="${ctx}/static/jquery/jquery-extensions/css/zTreeStyle/demo.css"/>--%>
<%--<link rel="stylesheet" type="text/css" href="${ctx}/static/jquery/jquery-extensions/css/zTreeStyle/zTreeStyle.css"/>--%>

<script type="text/javascript">
    var roleBuckets = {};
    var dataTable = null;
    var id_Array = new Array();

    function openDialog4Role(id){
        $( "#dialog-form" ).dialog( "open" );
        if(id!=""){
        	$.ajax({
                url:"${ctx}/system/getRoleById/"+id,
                cache:false,
                success:function(data){
                    var role = eval("("+data+")");
                    $( "#m_id" ).val(id);
                    $( "#roleName" ).val(role.roleName);
                    $( "#roleDesc" ).val(role.roleDesc);
                    parsePermissionIds(role.permissionIds);
                    initModifyPermission();
                }
            });
        }else{
            $( "#m_id" ).val("");
            $( "#roleName" ).val("");
            $( "#roleDesc" ).val("");
            clearCheckedNodes();
        }
    }

    function clearCheckedNodes(){
        var zTree = $.fn.zTree.getZTreeObj("tree");
        var nodes = zTree.getCheckedNodes(true);
        for (var j=0; j<nodes.length; j++) {
            zTree.checkNode(nodes[j],false,false,false);
        }
    }

    function parsePermissionIds(ids){
        id_Array = ids.split(",");
    }

    function initModifyPermission(){
        var zTree = $.fn.zTree.getZTreeObj("tree");

        clearCheckedNodes();

        for(var i=0;i<id_Array.length;i++){
            var node = zTree.getNodeByParam("id",id_Array[i],null);
            zTree.checkNode(node,true,false,true);
        }
    }

    Array.prototype.contains = function(obj) {
        var i = this.length;
        while (i--) {
            if (this[i] == obj) {
                return true;
            }
        }
        return false;
    }

    function deleteRole(id){
    	$.confirm(function(){
        	$.ajax({
                url:"${ctx}/system/deleteRole",
                data: {"m_id":id},
                success:function(data){
                	refreshRoleList();
                }
            });
 	   });
    }

    var m_id = $( "#m_id" );

    var setting = {
        data: {
            key: {
                title: "t"
            }
        },
        view: {
            selectedMulti: false
        },
        check: {
            enable: true
        }
    };


    var permissionsTree = ${permissionsTree};

    $(function () {
        setting.check.chkboxType = { "Y" : "s", "N" : "ps" };
        $.fn.zTree.init($("#tree"), setting,permissionsTree);
    	/*
        $("#tabs").tabs();


        dataTableSettings.bServerSide = true ;
        dataTableSettings.sAjaxSource = "${ctx}/system/getRoles" ;
        dataTableSettings.fnServerData = function(sSource, aoData, fnCallback){
            util.postData4DT(sSource, aoData, fnCallback);
        };
        dataTableSettings.aoColumns = [
            { "mData": "roleName","sClass": "center", "sTitle": "角色名称" },
            { "mData": "roleDesc","sClass": "center", "sTitle": "角色描述" },
            { "mData": "permissionsString","sClass": "center", "sTitle": "权限描述" },
            { "mData":"id",
                "sClass": "center",
                "sTitle": "操作",
                "bSearchable": false,
                "bStorable": false,
                "bSortable": false,
                "fnRender": function (obj) {
                    roleBuckets[obj.aData.id] = obj.aData;
                    return '<a flag=\"'+obj.aData.id+'\" href=\"javascript:void(0)\" onclick=\"openDialog4Role('+obj.aData.id+')\">编辑</a> '
                            + ' <a href=\"javascript:void(0)\" onclick=\"deleteRole('+obj.aData.id+')\">删除</a>';
                }
            }
        ];

        dataTable = $('#roleListTable').dataTable(dataTableSettings);
		*/
        var m_roleName = $( "#roleName" );

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 500,
            width: 650,
            modal: true,
            buttons: {
                "保存": function() {

                    var bValid = true;
                    m_roleName.removeClass( "ui-state-error" );

                    //bValid = bValid && checkRequired( m_roleName, "角色名称");

                    var treeObj = $.fn.zTree.getZTreeObj("tree");
                    var nodes = treeObj.getCheckedNodes(true);
                    var v = "";
                    for (var i=0; i<nodes.length; i++) {
                        if(i!=0){
                            v += ",";
                        }
                        v += ""+nodes[i].id;
                    }
                    $("#permissionIds").val(v);
                    if ( bValid ) {
                        $.post("${ctx}/system/saveRole"
                                ,$('#roleForm').serialize()
                                ,function(a){
                                    if(a){
                                        var c = eval("("+a+")");
                                        if(roleBuckets[c.id]){
                                            roleBuckets[c.id] = c;
                                        }
                                        $("#searchForm").submit();
                                    }
                                    $( "#dialog-form" ).dialog( "close" );
                                });
                    }
                },
                "取消": function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                m_roleName.val( "" ).removeClass( "ui-state-error" );
            }
        });
    });

    //===========================MJWL start================================
   	function refreshRoleList(){
        $("#roleList").jqGrid('setGridParam',{postData:$("#searchForm").serializeObject()}).trigger("reloadGrid");
    }
    
   	$(function () {
        $("#btn_search").bind("click", function(){
        	refreshRoleList();
        });

        $("#roleList").jqGrid({
            datatype: "json",
            url : "${ctx}/system/queryRoles",
			mtype: "POST",
            width:"100%",
            height:"100%",
            colNames: ['操作','角色名称','角色描述', '权限描述'],
            colModel: [
                {name:'act',index:'userId',search:false,sortable:false,editable:false
                    ,formatter:function(cellvalue, options, rowObject){ return tagLinkEdit("openDialog4Role("+rowObject.id+")")+" "+tagLinkDel("deleteRole("+rowObject.id+")");}
                },
                {name: 'roleName', index: 'roleName',sortable:false},
                {name: 'roleDesc', index: 'roleDesc',sortable:false},
                {name: 'permissionsString', index: 'permissionsString',sortable:false}
            ],
            rowNum: 10,
            rowList:[10,20,30],
            pager: '#pager',
            imgpath: 'images',
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            autowidth:true,
            jsonReader: {
                repeatitems : false,
                id: "id"
            },
            caption: "角色查询结果列表"
        });
   	});
    //===========================MJWL end================================

</script>

<div id="dialog-form" title="角色管理" style="display: none;">
    <p class="validateTips"></p>
    <form:form id="roleForm" modelAttribute="sysRoleVO" action="${ctx}/system/saveRole" method="post" class="form-horizontal">
        <input type="hidden" name="id" id="m_id" value="${sysRoleVO.id}"/>
        <input type="hidden" name="permissionIds" id="permissionIds" value="${sysRoleVO.permissionIds}"/>
        <table class="searchtable">
            <tbody>
            <tr>
                <td class="bg_gray">角色名称</td>
                <td>
                    <input type="text" id="roleName" name="roleName" maxlength="10"
                           value="${sysRoleVO.roleName}" class="text_medium"/>
                </td>
            </tr>

            <tr>
                <td class="bg_gray">角色描述</td>
                <td>
                    <input type="text" name="roleDesc" id="roleDesc" value="${sysRoleVO.roleDesc}"
                           maxlength="25" class="text_medium"/>
                </td>
            </tr>

            <tr>
                <td class="bg_gray">权限设置</td>
                <td>
                    <div class="zTreeDemoBackground left">
                        <ul id="tree" class="ztree"></ul>
                    </div>
                    <%--<form:bscheckboxes path="permissionList" items="${allPermissions}" itemLabel="permissionDesc" itemValue="id"/>--%>
                </td>
            </tr>
        </tbody>
        </table>
    </form:form>
</div>

<div class="panel_container">
    <div class="panel">
        <form action="" method="POST" id="searchForm">
        <div class="panel_header">
            <div><h2>角色管理</h2></div>
        </div>
        <div class="panel_body">
            <div>
                <div class="info_item"><span>角色名称:</span><input type="text" name="roleName" id="s_roleName"></div>
            </div>
        </div>
        <div class="panel_footer">
            <div>
                <input type="button" value="查询" class="btn_blue" id="btn_search">&nbsp;
                <input type="button" value="创建角色" class="btn_blue" id="btn_createRole" onclick="openDialog4Role('')">&nbsp;
            </div>
        </div>
        </form>
    </div>

    <div class="panel">
        <div class="panel_body">
            <div>
                <table id="roleList"></table>
                <div id="pager"></div>
            </div>
        </div>
    </div>
</div>
